import prisma from "@/src/db/db";
import { NextResponse } from "next/server";
import Stripe from "stripe";
import { Resend } from "resend";
import { revalidatePath } from "next/cache";
import PurchaseReceipt from "@/src/email/PurchaseReceipt";
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY);

const resend = new Resend(process.env.RESEND_API_KEY);

export const POST = async (req: Request, res: Response) => {
  const event = await stripe.webhooks.constructEvent(
    await req.text(),
    req.headers.get("stripe-signature"),
    process.env.STRIPE_WEBHOOK_SECRET
  );
  if (event.type === "charge.succeeded") {
    const charge = event.data.object;
    console.log(charge.metadata, 233);

    const productId = charge.metadata.productId;
    const email = charge.billing_details.email;
    const pricePaidInCents = charge.amount;

    const product = await prisma.product.findUnique({
      where: { id: productId },
    });
    if (!product || !email) {
      return new NextResponse("bad request", { status: 400 });
    }
    const userFields = {
      email,
      orders: { create: { productId, pricePaidInCents } },
    };
    const {
      orders: [order],
    } = await prisma.user.upsert({
      where: { email }, // 如果email存在就更新，不存在就创建
      create: userFields,
      update: userFields,
      select: { orders: { orderBy: { createAt: "desc" }, take: 1 } },
    });
    revalidatePath("/admin");

    const doenloadVerification = await prisma.downloadVerification.create({
      data: {
        productId,
        expiresAt: new Date(Date.now() + 1000 * 60 * 60 * 24),
      },
    });

    await resend.emails.send({
      from: `Support <${process.env.SENDER_EMAIL}>`,
      to: email,
      subject: "Order Confirmation",
      react: PurchaseReceipt({
        order,
        product,
        downloadVerificationId: doenloadVerification.id,
      }),
      // <PurchaseReceipt
      //   order={order}
      //   product={product}
      //   downloadVerificationId={doenloadVerification.id}
      // />
      // ),
    });
  }

  return new NextResponse();
};
